package server

import (
	"gameserver/server/redisutil"

	"gitee.com/night-tc/gobige/entity"
	"gitee.com/night-tc/gobige/global"
	"gitee.com/night-tc/gobige/msgdef"
	"gitee.com/night-tc/gobige/msgdef/protomsg"
	"gitee.com/night-tc/gobige/serverMgr"
)

/*
发消息给玩家有状态的服务器 (同步消息)
例：Center发给Lobby
*/
func PostPlayerSyncByStatus(pid uint64, stype global.ServerTypeEnum, msg msgdef.IMsg,
	orderid uint64, prefix string,
) (result *protomsg.RouteMsgSrvRet, err error) {
	sessutil := redisutil.NewGateSession(pid)
	nttid, err := sessutil.GetEntityID()
	if err != nil {
		return nil, err
	}
	nttutil := entity.NewRedisUtilEntity(nttid)
	srvid, spid, err := nttutil.GetSrvInfoByStype(stype)
	if err != nil {
		return nil, err
	}
	return global.PostSrvSync(srvid, msg,
		global.SrvSetPID(pid),
		global.SrvSetEID(spid, nttid),
		global.SrvSetOrderID(orderid),
		global.SrvSetPrefix(prefix))
}

/*
发消息给玩家有状态的服务器 (异步消息)
例：Linker发给Lobby
*/
func PostPlayerAsyncByStatus(
	pid uint64, stype global.ServerTypeEnum, msg msgdef.IMsg,
	fcall func(msgret *protomsg.RouteMsgSrvRet, err error),
) (err error) {
	sessutil := redisutil.NewGateSession(pid)
	nttid, err := sessutil.GetEntityID()
	if err != nil {
		return err
	}
	nttutil := entity.NewRedisUtilEntity(nttid)
	srvid, spid, err := nttutil.GetSrvInfoByStype(stype)
	if err != nil {
		return err
	}
	global.PostSrvAsync(srvid, msg,
		fcall,
		global.SrvSetPID(pid),
		global.SrvSetEID(spid, nttid),
	)
	return nil
}

/*
发消息给别的服务器,可以带玩家ID （异步消息）
例：Lobby发给Center
*/
func PostSrvAsync(pid uint64, stype global.ServerTypeEnum, msg msgdef.IMsg, fcall func(msgret *protomsg.RouteMsgSrvRet, err error)) error {
	dirmgr := global.GetSrvInst().(serverMgr.IExt).GetDirMgr()
	cfginst := global.GetCfgInst()
	srvinfo, err := dirmgr.GetServerByType(cfginst.GetGroupID(), stype)
	if err != nil {
		return err
	}
	global.PostSrvAsync(srvinfo.GetServerID(), msg,
		fcall,
		global.SrvSetPID(pid))
	return nil
}
